﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using JPCloudPrinter.Utils;

namespace JPCloudPrinter {
    public partial class FrmDownload : CCSkinMain {
        private string url = "";
        private string filePath = "";
        
        public FrmDownload()
        {
            InitializeComponent();
        }

        public FrmDownload(string url,string filePath) : this()
        {
            //准备下载文件
            this.url = url;
            this.filePath = filePath;
        }

        private void FrmProgress_Load(object sender, EventArgs e)
        {
            //通过http下载，并保存在downloads/年份/月份
            ThreadPool.QueueUserWorkItem(new WaitCallback(Download),null);
        }

        private void Download(object obj)
        {
            HttpUtil.Download(url, filePath, new HttpUtil.DownloadProgressCallback((progress, total) =>
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    progressBar1.Value = Convert.ToInt32(progress * progressBar1.Maximum / total);

                    lbText.Text = progress + "/" + total;
                }));
            }));
                        
            this.Invoke(new MethodInvoker(() =>
            {
                lbText.Text = "下载完毕";

                if (MessageBox.Show("是否打开下载文件?","系统提示",MessageBoxButtons.YesNo)==DialogResult.Yes)
                {                
                    System.Diagnostics.Process.Start("explorer", filePath);

                    this.Close();
                }
            }));
        }
    }
}